const AUTH = require('../../utils/auth')
const WXAPI = require('apifm-wxapi');

// pages/main/index.js
Page({
  data: {
    shopInfo:wx.getStorageSync('shopInfo'),
    kaiping: true
  },

  onLoad(options) { 
    //如果是首页选择店面跳转,则不读取最近的门店数据,否则若是直接点开点餐,算法自动选择最近门店(用全局变量routerType控制,若为main,则不读取,否则读取)
    if(wx.getStorageSync('routerType')!='main'){//直接点开点餐,匹配最近
      this.getshopInfo()// 读取最近的门店数据
    }else{//首页选店,从缓存中提取
      this.setData({
        shopInfo: wx.getStorageSync('shopInfo')
      })
    }
    this.getBanners();//获取轮播图图片
    this.getUserAmount();//获取用户积分余额
  },
  onShow(){
    this.setData({//读取缓存的商店信息
      shopInfo: wx.getStorageSync('shopInfo')
    })
  },
  //读取地理位置进而获取门店信息
  getshopInfo() {
    wx.getLocation({
      type: 'wgs84',//返回gps坐标,获取经纬度
      success: (res) => {
        this.data.latitude = res.latitude
        this.data.longitude = res.longitude
        this.fetchShops(res.latitude, res.longitude, '')
      },
      fail: (e) => {//获取失败
        AUTH.checkAndAuthorize('scope.userLocation')
      },
      complete: () => { }
    });
  },
  //根据地理位置、kw（关键字）匹配最近最符合的商店信息，以及相应的门店列表【很奇怪，我调试的时候只有一条门店信息qwq】
  async fetchShops(latitude, longitude, kw) {
    const res = await WXAPI.fetchShops({
      curlatitude: latitude,
      curlongitude: longitude,
      nameLike: kw,
      pageSize: 1
    })
    // console.log(res);

    if (res.code == 0) {
      res.data.forEach(ele => {
        ele.distance = ele.distance.toFixed(1)//距离保留1位小数
      })
      this.setData({
        shops: res.data,
        shopInfo: res.data[0],//第一个即优选店铺
        shopIsOpened: this.checkIsOpened(res.data[0].openingHours)
      })
      //存入缓存
      wx.setStorage({
        key: 'shopInfo',
        data: res.data[0]
      });
    }
  },
  //检查店铺是否在营业时间[例如：openingHours 08:00-23:00]
  checkIsOpened(openingHours) {
    const date = new Date();
    const startTime = openingHours.split('-')[0]
    const endTime = openingHours.split('-')[1]
    const dangqian = date.toLocaleDateString('chinese', { hour12: false })//获取当前时间，24小时制

    const dq = dangqian.split(":")
    const a = startTime.split(":")
    const b = endTime.split(":")

    const dqdq = date.setHours(dq[0], dq[1])
    const aa = date.setHours(a[0], a[1])
    const bb = date.setHours(b[0], b[1])

    return aa < dqdq && dqdq < bb
  },
  //更改配送方式
  changePeisongType(e) {
    const peisongType = e.currentTarget.dataset.type
    this.setData({ peisongType })
  },
  //异步加载获取轮播图数据
  async getBanners() {
    const res = await WXAPI.banners()
    // console.log(res);
    if (res.code == 0) {
      this.setData({
        banners: res.data
      })
    }
  }, 
  //获取用户积分余额等信息
  async getUserAmount() {
    const res = await WXAPI.userAmount(wx.getStorageSync('token'))
    if (res.code == 0) {
      this.setData({
        balance: res.data.balance,
        score: res.data.score
      })
    }
  },
  goScorelog() {
    wx.navigateTo({
      url: '/pages/score/logs',
    })
  }
})
